package com.example.logindb.sevices;


import com.alibaba.fastjson.JSONArray;
import com.example.logindb.entity.Location;
import com.example.logindb.entity.Online;
import com.example.logindb.repository.LocationRepository;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import okhttp3.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class LocationServiceImpl implements LocationService {
    private LocationRepository locationRepository;
    public LocationServiceImpl(LocationRepository locationRepository)
    {
        this.locationRepository = locationRepository;
    }


    @Override
    public void updateLocation(Location location) {
        Location bdlocation = new Location();
        bdlocation.setLocid(location.getLocid());
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject("http://api.map.baidu.com/geoconv/v1/?coords="+location.getLon()+","+location.getLat()+"&from=1&to=5&ak=bdKz6w86x9y7wfOT2Zw2yARuwBfU10FJ", String.class);
        System.out.println(result);
        JSONObject root = JSONObject.parseObject(result);
        System.out.println(root);
        JSONArray data = root.getJSONArray("result");
        JSONObject data1 = data.getJSONObject(0);
        bdlocation.setLon(data1.getDouble("x"));
        bdlocation.setLat(data1.getDouble("y"));
        System.out.println(bdlocation);
        locationRepository.save(bdlocation);
        //locationRepository.save(location);
    }

    @Override
    public Location findAllById(Integer id) {
        return locationRepository.findAllByLocid(id);
    }

    @Override
    public List<Location> findAll() {
        return locationRepository.findAll();
    }

    @Override
    public String getAddress(Double lon, Double lat) {

        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject("https://restapi.amap.com/v3/geocode/regeo?output=json&location=" + lon + "," + lat + "&key=be535b01ade695135c7e3b7301f02320", String.class);
        JSONObject root = JSONObject.parseObject(result);

        JSONObject data = root.getJSONObject("regeocode");
        String address = data.getString("formatted_address");
        System.out.println(address);

        return address;

    }

    @Override
    public void deleteLocationById(int id) {
        locationRepository.deleteById(id);
    }


    public class NetworkHandler {
        /**
         * JSON format
         */
        public static final MediaType JSON = MediaType.get("application/json");

        public static final MediaType IMAGE = MediaType.parse("image/*");


        /**
         * Construct
         */
        private NetworkHandler(){}

        /**
         * Default OkHHTP Client
         */
        public static OkHttpClient GetOkHttpClient() {
            return GetOkHttpClient(60, 60, 60);
        }

        /**
         * Custom OkHTTP Client
         * @param connectTimeout
         * @param readTimeOut
         * @param writeTimeOut
         * @return
         */
        public static OkHttpClient GetOkHttpClient(int connectTimeout, int readTimeOut, int writeTimeOut) {
            OkHttpClient.Builder builder = new okhttp3.OkHttpClient().newBuilder();
            builder.connectTimeout(connectTimeout, TimeUnit.SECONDS);
            builder.readTimeout(readTimeOut, TimeUnit.SECONDS);
            builder.writeTimeout(writeTimeOut, TimeUnit.SECONDS);
            return builder.build();
        }

        public static String get(String url) {
            OkHttpClient client = GetOkHttpClient();
            Headers headers = new Headers.Builder().build();
            Request request = new Request.Builder()
                    .url(url)
                    .headers(headers)
                    .get()
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if (response.body() != null)
                    return response.body().string();
                else
                    return "NetworkHandler::NullPointerException";
            }
            catch (IOException e){
                System.out.println("NetworkHandler::IOException: " + e.getMessage());
                return "IOException:" + e.getMessage();
            }
        }

        public static String post(String url, String jsonBody) {
            OkHttpClient client = GetOkHttpClient();
            RequestBody body = RequestBody.create(jsonBody, JSON);
            Headers headers = new Headers.Builder().build();

            Request request = new Request.Builder()
                    .url(url)
                    .headers(headers)
                    .post(body)
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if (response.body() != null) {
                    return response.body().string();
                }
                else
                    return "NetworkHandler::NullPointerException";
            }
            catch (IOException e){
                System.out.println("NetworkHandler::IOException: " + e.getMessage());
                return "IOException:" + e.getMessage();
            }
        }

        public static String UploadImage(OkHttpClient client, String url, File img, String id){
            RequestBody imgRequest = RequestBody.create(img, IMAGE);

            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.ALTERNATIVE)
                    .addFormDataPart("id", id)
                    .addFormDataPart("image", "image.jpg", imgRequest)
                    .build();

            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if (response.body() != null) {
                    return response.body().string();
                }
                else
                    return "NetworkHandler::NullPointerException";
            }
            catch (IOException e){
                return "IOException:" + e.getMessage();
            }
        }
    }



//    @Override
//    public List<String> findGeojsonByBlindID(int id) {
//        return routeRepository.findGeoJsonByBlindid(id);
//    }


}